<template>
  <div class="analytics-container">
    <h1 class="analytics-title">卫生间设施数据分析</h1>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="data-summary-card">
          <template #header>
            <div class="card-header">
              <span>数据概览</span>
              <el-tag type="info" size="small">{{ totalFacilities }} 个设施</el-tag>
            </div>
          </template>
          <div class="data-summary">
            <el-row :gutter="20">
              <el-col :span="6" v-for="(item, index) in summaryData" :key="index">
                <div class="summary-item">
                  <div class="summary-icon" :style="{backgroundColor: item.color}">
                    <el-icon><component :is="item.icon" /></el-icon>
                  </div>
                  <div class="summary-info">
                    <div class="summary-value">{{ item.value }}</div>
                    <div class="summary-label">{{ item.label }}</div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>卫生间类型分布</span>
            </div>
          </template>
          <div class="chart-container" id="bathroomTypeChart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>性别分布</span>
            </div>
          </template>
          <div class="chart-container" id="genderChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>设施特性分析</span>
            </div>
          </template>
          <div class="chart-container" id="featuresChart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>收费情况分析</span>
            </div>
          </template>
          <div class="chart-container" id="feeChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>厕位数量分布</span>
            </div>
          </template>
          <div class="chart-container" id="toiletCountChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>开放日分析</span>
            </div>
          </template>
          <div class="chart-container" id="openDaysChart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Query from '@arcgis/core/rest/support/Query.js'
import {  Location, Money, Calendar, Setting, DataAnalysis } from '@element-plus/icons-vue'

// 数据状态
const totalFacilities = ref(0)
const bathroomTypes = reactive(new Map())
const genderDistribution = reactive(new Map())
const accessibleCount = ref(0)
const freeCount = ref(0)
const toiletCounts = reactive<number[]>([])
const openDaysData = reactive<Record<string, number>>({
  '周一': 0,
  '周二': 0,
  '周三': 0,
  '周四': 0,
  '周五': 0,
  '周六': 0,
  '周日': 0
})
const feeData = reactive<number[]>([])
// 图表实例
let bathroomTypeChart: echarts.ECharts | null = null
let genderChart: echarts.ECharts | null = null
let featuresChart: echarts.ECharts | null = null
let feeChart: echarts.ECharts | null = null
let toiletCountChart: echarts.ECharts | null = null
let openDaysChart: echarts.ECharts | null = null

// 数据概览
const summaryData = reactive([
  { label: '设施总数', value: 0, icon: 'Toilet', color: '#409EFF' },
  { label: '无障碍设施', value: 0, icon: 'Location', color: '#67C23A' },
  { label: '免费设施', value: 0, icon: 'Money', color: '#E6A23C' },
  { label: '平均厕位数', value: 0, icon: 'DataAnalysis', color: '#F56C6C' }
])

// 初始化数据
onMounted(async () => {
  await fetchFacilityData()
  initCharts()
  window.addEventListener('resize', handleResize)
})

// 获取设施数据
const fetchFacilityData = async () => {
  try {
    // 创建卫生间设施图层
    const bathroomLayer = new FeatureLayer({
      url: 'https://services.arcgis.com/Jaqp8M1tVnnHQ5RM/arcgis/rest/services/Bathroom_FacilitiesManagementSystem/FeatureServer/0',
      outFields: ['*']
    })

    // 查询所有设施
    const query = new Query({
      where: '1=1',
      outFields: ['*'],
      returnGeometry: false
    })

    const result = await bathroomLayer.queryFeatures(query)
    const features = result.features

    if (features && features.length > 0) {
      totalFacilities.value = features.length
      summaryData[0].value = features.length

      // 重置数据
      bathroomTypes.clear()
      genderDistribution.clear()
      accessibleCount.value = 0
      freeCount.value = 0
      toiletCounts.length = 0
      Object.keys(openDaysData).forEach(day => openDaysData[day] = 0)
      feeData.length = 0

      // 处理数据
      let totalToiletCount = 0

      features.forEach(feature => {
        const attrs = feature.attributes

        // 卫生间类型
        const type = attrs.BathroomType || '未知'
        bathroomTypes.set(type, (bathroomTypes.get(type) || 0) + 1)

        // 性别分布
        const gender = attrs.gender || '未知'
        genderDistribution.set(gender, (genderDistribution.get(gender) || 0) + 1)

        // 无障碍设施
        if (attrs.is_accessible === '有') {
          accessibleCount.value++
        }

        // 免费情况
        if (attrs.is_free === '是') {
          freeCount.value++
        } else {
          // 收费情况
          const fee = parseFloat(attrs.fee) || 0
          feeData.push(fee)
        }

        // 厕位数量
        const toiletCount = parseInt(attrs.toilet_count) || 0
        toiletCounts.push(toiletCount)
        totalToiletCount += toiletCount

        // 开放日
        if (attrs.open_days) {
          const days = attrs.open_days.split(',')
          days.forEach((day: string) => {
            if (openDaysData[day] !== undefined) {
              openDaysData[day]++
            }
          })
        }
      })

      // 更新概览数据
      summaryData[1].value = accessibleCount.value
      summaryData[2].value = freeCount.value
      summaryData[3].value = totalFacilities.value > 0 ? Math.round(totalToiletCount / totalFacilities.value) : 0

      ElMessage.success('数据加载成功')
    } else {
      ElMessage.warning('未找到设施数据')
    }
  } catch (error) {
    console.error('获取设施数据失败:', error)
    ElMessage.error('获取设施数据失败')
  }
}

// 初始化图表
const initCharts = () => {
  // 卫生间类型分布图表
  bathroomTypeChart = echarts.init(document.getElementById('bathroomTypeChart'))
  const bathroomTypeData = Array.from(bathroomTypes.entries()).map(([name, value]) => ({ name, value }))
  bathroomTypeChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: Array.from(bathroomTypes.keys())
    },
    series: [
      {
        name: '卫生间类型',
        type: 'pie',
        radius: '55%',
        center: ['50%', '60%'],
        data: bathroomTypeData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })

  // 性别分布图表
  genderChart = echarts.init(document.getElementById('genderChart'))
  const genderData = Array.from(genderDistribution.entries()).map(([name, value]) => ({ name, value }))
  genderChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: Array.from(genderDistribution.keys())
    },
    series: [
      {
        name: '性别分布',
        type: 'pie',
        radius: '55%',
        center: ['50%', '60%'],
        data: genderData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })

  // 设施特性分析图表
  featuresChart = echarts.init(document.getElementById('featuresChart'))
  featuresChart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['无障碍设施', '免费设施']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '设施数量',
        type: 'bar',
        data: [
          { value: accessibleCount.value, itemStyle: { color: '#67C23A' } },
          { value: freeCount.value, itemStyle: { color: '#E6A23C' } }
        ],
        label: {
          show: true,
          position: 'top'
        }
      }
    ]
  })

  // 收费情况分析图表
  feeChart = echarts.init(document.getElementById('feeChart'))
  const feeChartData = [
    { value: freeCount.value, name: '免费' },
    { value: totalFacilities.value - freeCount.value, name: '收费' }
  ]
  feeChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['免费', '收费']
    },
    series: [
      {
        name: '收费情况',
        type: 'pie',
        radius: '55%',
        center: ['50%', '60%'],
        data: feeChartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })

  // 厕位数量分布图表
  toiletCountChart = echarts.init(document.getElementById('toiletCountChart'))

  // 计算厕位数量分布
  const toiletCountDistribution: Record<number, number> = {}
  toiletCounts.forEach(count => {
    toiletCountDistribution[count] = (toiletCountDistribution[count] || 0) + 1
  })

  const toiletCountKeys = Object.keys(toiletCountDistribution).sort((a, b) => parseInt(a) - parseInt(b))
  const toiletCountValues = toiletCountKeys.map(key => toiletCountDistribution[parseInt(key)])

  toiletCountChart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: toiletCountKeys,
      name: '厕位数量'
    },
    yAxis: {
      type: 'value',
      name: '设施数量'
    },
    series: [
      {
        name: '厕位数量分布',
        type: 'bar',
        data: toiletCountValues,
        itemStyle: {
          color: function(params: { value: number }) {
            // 根据值生成不同深浅的颜色
            const colorList = ['#91cc75', '#67C23A', '#4CAF50', '#388E3C', '#2E7D32', '#1B5E20']
            const index = Math.min(Math.floor(params.value / 2), colorList.length - 1)
            return colorList[index]
          }
        },
        label: {
          show: true,
          position: 'top'
        }
      }
    ]
  })

  // 开放日分析图表
  openDaysChart = echarts.init(document.getElementById('openDaysChart'))
  const openDaysKeys = Object.keys(openDaysData)
  const openDaysValues = openDaysKeys.map(key => openDaysData[key])

  openDaysChart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: openDaysKeys
    },
    yAxis: {
      type: 'value',
      name: '设施数量'
    },
    series: [
      {
        name: '开放日分布',
        type: 'bar',
        data: openDaysValues,
        itemStyle: {
          color: function(params: { dataIndex: number }) {
            // 工作日和周末使用不同颜色
            const colorList = ['#409EFF', '#409EFF', '#409EFF', '#409EFF', '#409EFF', '#F56C6C', '#F56C6C']
            return colorList[params.dataIndex]
          }
        },
        label: {
          show: true,
          position: 'top'
        }
      }
    ]
  })
}

// 处理窗口大小变化
const handleResize = () => {
  bathroomTypeChart?.resize()
  genderChart?.resize()
  featuresChart?.resize()
  feeChart?.resize()
  toiletCountChart?.resize()
  openDaysChart?.resize()
}
</script>

<style scoped>
.analytics-container {
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.analytics-title {
  color: #409EFF;
  margin-bottom: 20px;
  font-size: 24px;
  text-align: center;
  position: relative;
}

.analytics-title::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 100px;
  height: 3px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  border-radius: 3px;
}

.chart-row {
  margin-top: 20px;
}

.chart-card {
  height: 400px;
  margin-bottom: 20px;
}

.chart-container {
  height: 320px;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.data-summary-card {
  margin-bottom: 20px;
}

.data-summary {
  padding: 10px 0;
}

.summary-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: 100px;
}

.summary-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 15px;
  color: white;
  font-size: 24px;
}

.summary-info {
  flex: 1;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.summary-label {
  font-size: 14px;
  color: #909399;
}
</style>